<?php

class Session
{
	/**
	 * Start a session.
	 * 
	 * This will start a new session or pick up an existing one.
	 */
	static public function start()
	{
		session_name(self::getSessionName());
		session_start();
		if (!isset($_SESSION['QUIBBOX_GENERATED_SID'])) {
			self::regenerate();
		}
	}
	
	/**
	 * End the current session.
	 * 
	 * This will end any currently active session and also delete all traces of
	 * it from both the server and the client.
	 */
	static public function end()
	{
		// Make sure nobody is able to access the session information anymore
		$_SESSION = array();
		
		// Delete the session cookie if there is one
		if (session_id() !== '' || isset($_COOKIE[session_name()])) {
			 setcookie(session_name(), '', time()-42000, '/');
		}
		
		// Delete the session from the session storage
		session_destroy();
	}
	
	static public function currentUser()
	{
		return 'justmoon';
	}
	
	/**
	 * Changes the session ID.
	 */
	static public function regenerate()
	{
		session_regenerate_id();
		$_SESSION['QUIBBOX_GENERATED_SID'] = true;
	}
	
	/**
	 * Retrieves the session name.
	 *
	 * This will try to find out the current session name from the database. If
	 * there isn't one yet, it will generate one.
	 */
	static public function getSessionName()
	{
		$name = Config::get('session_name');
		if ($name !== null) {
			return $name;
		} else {
			$name = 'qbbx_sess_'.substr(md5(rand()*microtime(true)), 0, 6);
			Config::set('session_name', $name, true);
			return $name;
		}
	}
}
?>